package com.start.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.start.admin.entity.StartSysUser;
import com.start.admin.entity.StartSysUserRole;
import com.start.admin.mappers.SysUserMapper;
import com.start.admin.mappers.SysUserRoleMapper;
import com.start.admin.service.StartSysUserRoleService;
import com.start.admin.vo.StartUserRoleVo;
import com.start.common.exceptions.StartBusException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StartSysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, StartSysUserRole> implements StartSysUserRoleService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public List<StartUserRoleVo> getRoleListByUserId(String userId) {
        QueryWrapper<StartUserRoleVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return getBaseMapper().listUserRole(queryWrapper);
    }

    @Override
    public boolean userHasRoles(String userId, String[] roles) {
        List<String> roleCodes = Arrays.stream(roles).distinct().filter(StringUtils::isNotBlank).collect(Collectors.toList());
        QueryWrapper<StartUserRoleVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.in("code", roleCodes);
        return baseMapper.countUserRole(queryWrapper) > 0;
    }

    @Override
    public void saveUserRole(String userId, String[] roleIds) {
        if (StringUtils.isEmpty(userId)) throw new StartBusException("用户名不能为空");
        StartSysUser startSysUser = sysUserMapper.selectById(userId);
        if (startSysUser == null) throw new StartBusException("用户不存在");
        LambdaQueryWrapper<StartSysUserRole> wrapperRole = new LambdaQueryWrapper<>();
        wrapperRole.eq(StartSysUserRole::getUserId, userId);
        remove(wrapperRole);
        if (roleIds.length < 1) return;
        List<StartSysUserRole> userRoles = new ArrayList<>();
        for (String roleId : roleIds) {
            StartSysUserRole userRole = new StartSysUserRole();
            if (StringUtils.isEmpty(roleId)) continue;
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            userRoles.add(userRole);
        }
        if (userRoles.size() < 1) return;
        saveBatch(userRoles, 20);
    }

    @Override
    public List<StartSysUserRole> listByUserId(String userId) {
        LambdaQueryWrapper<StartSysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StartSysUserRole::getUserId, userId);
        return list(wrapper);
    }
}
